<template>
  <div class="chart-container">
    <div class="pie-charts">
      <div ref="userChartContainer" class="chart-box"></div>
      <div ref="newUserChartContainer" class="chart-box"></div> <!-- 新增的图表容器 -->
      <div ref="articlePieContainer" class="chart-box"></div>
    </div>
    <div ref="articleBarContainer" class="bar-chart-box"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import request from "@/api/request";
import { ElMessage } from "element-plus";

// 图表容器引用
const userChartContainer = ref(null)
const articlePieContainer = ref(null)
const articleBarContainer = ref(null)
const newUserChartContainer = ref(null)
let newUserChart = null
let userChart = null
let articlePieChart = null
let articleBarChart = null

// 获取用户数据并渲染图表
const fetchUserDataAndRenderChart = async () => {
  try {
    const res = await request.get('/admin/userList', {
      params: {
        pageNum: 1,
        pageSize: 1000,
        username: '',
        email: '',
      }
    })

    const users = res.data.items
    const totalUsers = res.data.total

    if (users.length === 0) {
      console.log('不存在用户数据')
      return
    }

    // 用户饼图配置
    const option = {
      title: {
        text: `用户统计\n总数: ${totalUsers}`,
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16,
          fontWeight: 'bold'
        },
        subtextStyle: {
          color: '#aaa'
        }
      },
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(0,0,0,0.7)',
        borderColor: 'rgba(255,255,255,0.2)',
        textStyle: {
          color: '#fff'
        }
      },
      series: [{
        name: '用户统计',
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: 'rgba(0,0,0,0.3)',
          borderWidth: 2,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
            color: '#fff'
          },
          itemStyle: {
            shadowBlur: 20,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: [{
          value: totalUsers,
          // name: '总用户数',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }]
      }]
    }

    if (userChart) {
      userChart.setOption(option)
    } else {
      userChart = echarts.init(userChartContainer.value)
      userChart.setOption(option)
    }

  } catch (error) {
    console.error('获取用户数据失败:', error)
  }
}

// 新增获取本月新用户数据方法
const fetchNewUserDataAndRenderChart = async () => {
  try {
    const res = await request.get('/user/countNewUsersThisMonth')
    const count = res.data

    const option = {
      title: {
        text: `本月新增用户\n数量: ${count}`,
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16,
          fontWeight: 'bold'
        },
        subtextStyle: {
          color: '#aaa'
        }
      },
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}',
        backgroundColor: 'rgba(0,0,0,0.7)',
        borderColor: 'rgba(255,255,255,0.2)',
        textStyle: {
          color: '#fff'
        }
      },
      series: [{
        name: '本月新增用户',
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: 'rgba(0,0,0,0.3)',
          borderWidth: 2,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
            color: '#fff'
          }
        },
        data: [{
          value: count,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#FF9A9E' },
              { offset: 1, color: '#FAD0C4' }
            ])
          }
        }]
      }]
    }

    if (newUserChart) {
      newUserChart.setOption(option)
    } else {
      newUserChart = echarts.init(newUserChartContainer.value)
      newUserChart.setOption(option)
    }
  } catch (error) {
    console.error('获取本月新用户数据失败:', error)
  }
}
// 获取文章数据并渲染图表
const fetchArticleDataAndRenderChart = async () => {
  try {
    const res = await request.get('/article/articleList', {
      params: {
        pageNum: 1,
        pageSize: 1000,
        title: '',
        categoryName: '',
      }
    })

    const articles = res.data.items
    const totalArticles = res.data.total

    if (articles.length === 0) {
      ElMessage.warning('不存在该文章')
      return
    }

    // 准备图表数据
    const categoryCount = {}
    articles.forEach(article => {
      categoryCount[article.categoryName] = (categoryCount[article.categoryName] || 0) + 1
    })

    const sortedByView = [...articles].sort((a, b) => b.viewCount - a.viewCount).slice(0, 10)
    const topTitles = sortedByView.map(article => article.title)
    const topViews = sortedByView.map(article => article.viewCount)

    // 文章分类饼图配置
    const pieOption = {
      title: {
        text: `文章分类统计\n总数: ${totalArticles}`,
        left: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(0,0,0,0.7)',
        borderColor: 'rgba(255,255,255,0.2)',
        textStyle: {
          color: '#fff'
        }
      },
/*      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          color: '#fff'
        }
      },*/
      series: [{
        name: '文章分类',
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['40%', '50%'],
        roseType: 'radius',
        itemStyle: {
          borderRadius: 8,
          borderColor: 'rgba(0,0,0,0.3)',
          borderWidth: 2,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            color: '#fff'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.entries(categoryCount).map(([name, value], index) => {
          // 为每个分类设置不同的渐变颜色
          const colorGradients = [
            ['#FF9A9E', '#FAD0C4'],  // 粉红渐变
            ['#A1C4FD', '#C2E9FB'],  // 蓝渐变
            ['#84FAB0', '#8FD3F4'],  // 绿蓝渐变
            ['#FFC3A0', '#FFAFBD'],  // 橙粉渐变
            ['#D4FC79', '#96E6A1'],  // 黄绿渐变
            ['#A6C1EE', '#FBC2EB'],  // 紫粉渐变
            ['#FFECD2', '#FCB69F'],  // 橙黄渐变
            ['#E0C3FC', '#8EC5FC'],  // 紫蓝渐变
            ['#F6D365', '#FDA085'],  // 金橙渐变
            ['#5EE7DF', '#B490CA']   // 青紫渐变
          ];

          return {
            name,
            value,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: colorGradients[index % colorGradients.length][0] },
                { offset: 1, color: colorGradients[index % colorGradients.length][1] }
              ])
            }
          };
        })
      }]
    }

    // 文章浏览量柱状图配置
    const barOption = {
      title: {
        text: '浏览量TOP10文章',
        left: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 18,
          fontWeight: 'bold'
        }
      },
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          shadowStyle: {
            color: 'rgba(255,255,255,0.1)'
          }
        },
        backgroundColor: 'rgba(0,0,0,0.7)',
        borderColor: 'rgba(255,255,255,0.2)',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: topTitles,
        axisLine: {
          lineStyle: {
            color: 'rgba(255,255,255,0.2)'
          }
        },
        axisLabel: {
          color: '#fff',
          rotate: 45,
          interval: 0,
          fontSize: 12
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        name: '浏览量',
        nameTextStyle: {
          color: '#fff'
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255,255,255,0.1)'
          }
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(255,255,255,0.2)'
          }
        },
        axisLabel: {
          color: '#fff'
        }
      },
      series: [{
        name: '浏览量',
        type: 'bar',
        barWidth: '60%',
        data: topViews,
        itemStyle: {
          color: function(params) {
            const colorList = [
              new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#f6d365' },
                { offset: 1, color: '#fda085' }
              ]),
              new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#5ee7df' },
                { offset: 1, color: '#b490ca' }
              ]),
              new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#a1c4fd' },
                { offset: 1, color: '#c2e9fb' }
              ]),
              new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ff9a9e' },
                { offset: 1, color: '#fad0c4' }
              ]),
              new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ffc3a0' },
                { offset: 1, color: '#ffafbd' }
              ])
            ];
            return colorList[params.dataIndex % colorList.length];
          },
          borderRadius: [4, 4, 0, 0],
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 5,
          shadowOffsetY: 3
        },
        label: {
          show: true,
          position: 'top',
          color: '#fff',
          formatter: '{c}'
        },
        emphasis: {
          itemStyle: {
            shadowColor: 'rgba(0, 0, 0, 0.5)',
            shadowBlur: 10
          }
        },
        animationDelay: function (idx) {
          return idx * 100;
        }
      }],
      animationEasing: 'elasticOut',
      animationDelayUpdate: function (idx) {
        return idx * 5;
      }
    }

    // 渲染图表
    if (articlePieChart) {
      articlePieChart.setOption(pieOption)
    } else {
      articlePieChart = echarts.init(articlePieContainer.value)
      articlePieChart.setOption(pieOption)
    }

    if (articleBarChart) {
      articleBarChart.setOption(barOption)
    } else {
      articleBarChart = echarts.init(articleBarContainer.value)
      articleBarChart.setOption(barOption)
    }

  } catch (error) {
    console.error('获取文章数据失败:', error)
    ElMessage.error('获取文章列表失败')
  }
}

// 生命周期钩子
onMounted(() => {
  if (userChartContainer.value) {
    userChart = echarts.init(userChartContainer.value)
    fetchUserDataAndRenderChart()
  }
  if (newUserChartContainer.value) {
    newUserChart = echarts.init(newUserChartContainer.value)
    fetchNewUserDataAndRenderChart()
  }
  if (articlePieContainer.value && articleBarContainer.value) {
    articlePieChart = echarts.init(articlePieContainer.value)
    articleBarChart = echarts.init(articleBarContainer.value)
    fetchArticleDataAndRenderChart()
  }
  window.addEventListener('resize', resizeCharts)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts)
  if (userChart) userChart.dispose()
  if (newUserChart) newUserChart.dispose()
  if (articlePieChart) articlePieChart.dispose()
  if (articleBarChart) articleBarChart.dispose()
})

// 响应式调整图表大小
function resizeCharts() {
  if (userChart) userChart.resize()
  if (newUserChart) newUserChart.resize()
  if (articlePieChart) articlePieChart.resize()
  if (articleBarChart) articleBarChart.resize()
}
</script>

<style scoped>
.chart-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  box-sizing: border-box;
  background: linear-gradient(135deg, #1e2a3a 0%, #2c3e50 100%);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  height: calc(100vh - 100px);
}

.pie-charts {
  display: flex;
  gap: 20px;
  width: 100%;
  height: 45%;
}

.chart-box {
  width: 33.33%; /* 修改为三等分 */
  height: 100%;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.bar-chart-box {
  width: 100%;
  height: 50%;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.chart-box:hover,
.bar-chart-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
}
</style>

